package abq2.jic.jic.plugin.operate.library;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.IListView;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.HashMap;

/**
 * 标准单据列表插件
 */
public class ReturnBook extends AbstractListPlugin implements Plugin {
    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        String operateKey = ((FormOperate) e.getSource()).getOperateKey();
        if (operateKey.equals("alreadyreturn")){
            IListView list = (IListView) this.getView();
            ListSelectedRow currentSelectedRowInfo = list.getCurrentSelectedRowInfo();
            Object primaryKeyValue = currentSelectedRowInfo.getPrimaryKeyValue();

            DynamicObject option = BusinessDataServiceHelper.loadSingle("abq2_books_borrow",
                    "billno," + //单据编号
                            "id," + //id值
                            "entryentity," + //单据体
                            "abq2_textfield222," + //借阅状态
                            "abq2_basedatafield," + //书籍信息
                            "creator" //借阅者
                    ,
                    new QFilter[]{new QFilter("id", QCP.equals, primaryKeyValue)});
            if (option.getString("abq2_textfield222").equals("已归还")){
                this.getView().showTipNotification("该书籍借阅单已经是已归还的状态了");
                return;
            }else if (option.getString("abq2_textfield222").equals("未同意")){
                this.getView().showTipNotification("该书籍借阅单还未同意借阅");
                return;
            }
            option.set("abq2_textfield222","已归还");
            DynamicObjectCollection books = option.getDynamicObjectCollection("entryentity");
            for (DynamicObject book : books) {
                long id = book.getLong("abq2_basedatafield.id");
                DynamicObject bookInfo = BusinessDataServiceHelper.loadSingle("abq2_books_info",
                        "id,abq2_integerfield,abq2_integerfield1",
                        new QFilter[]{new QFilter("id", QCP.equals, id)});
                bookInfo.set("abq2_integerfield", bookInfo.getInt("abq2_integerfield") + 1);
                SaveServiceHelper.update(bookInfo);
            }
            SaveServiceHelper.update(option);
            this.getView().showSuccessNotification("已设置为已归还");
            list.refresh();
        }
    }
}